package com.test.reggieadmin.model.dish;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.test.reggieadmin.R;
import com.test.reggieadmin.base.BaseActivity;
import com.test.reggieadmin.base.BaseRVAdapter;
import com.test.reggieadmin.base.BaseRVHolder;
import com.test.reggieadmin.base.GifSizeFilter;
import com.test.reggieadmin.bean.BaseBean;
import com.test.reggieadmin.bean.CategoryListBean;
import com.test.reggieadmin.bean.DishDetailsBean;
import com.test.reggieadmin.bean.EmployeeBean;
import com.test.reggieadmin.bean.State;
import com.test.reggieadmin.databinding.ActivityAddDishBinding;
import com.test.reggieadmin.http.API;
import com.yechaoa.yutils.GsonUtil;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 新增菜品
 */
public class AddDishActivity extends BaseActivity<ActivityAddDishBinding, AddDishPrensenter>
        implements AddDishView, View.OnClickListener {

    private List<DishDetailsBean.DataBean.FlavorsBean> flarors = new ArrayList<>();
    private BaseRVAdapter<DishDetailsBean.DataBean.FlavorsBean> adapter;
    private BasePopupView basePopupView;
    private String categoryId;
    private String image;
    private EmployeeBean employeeBean;
    private String id;
    private List<CategoryListBean.DataBean> flavorList;

    @Override
    protected AddDishPrensenter createPresenter() {
        return new AddDishPrensenter(this);
    }

    @Override
    protected void initView() {
        viewBinding.icHead.tvTitle.setText("添加菜品");
        viewBinding.icHead.llBack.setOnClickListener(this);
        viewBinding.btnSave.setOnClickListener(this);
        viewBinding.btnAddFlavor.setOnClickListener(this);
        viewBinding.tvCategoryId.setOnClickListener(this);
        viewBinding.iv.setOnClickListener(this);

        employeeBean = GsonUtil.GsonToBean(String.valueOf(API.kv.decodeString(State.employee)), EmployeeBean.class);
        id = getIntent().getStringExtra("id");
        categoryId = getIntent().getStringExtra("categoryId");

        presenter.categoryList(1);//根据条件查询分类数据

        if (id != null && !"".equals(id)) {
            viewBinding.icHead.tvTitle.setText("修改菜品");
            YUtils.showLoading("加载中...");
            presenter.dishDetails(id);//根据id查询菜品信息和对应的口味信息
        }
    }

    @Override
    protected void initData() {
        adapter = new BaseRVAdapter<DishDetailsBean.DataBean.FlavorsBean>(R.layout.item_flavor) {
            @Override
            public void onBindVH(BaseRVHolder holder, DishDetailsBean.DataBean.FlavorsBean data, int position) {
                TextView tv_delete = holder.getView(R.id.tv_delete);

                holder.setText(R.id.tv_name, data.getName());
                holder.setText(R.id.tv_value, data.getValue());

                tv_delete.setOnClickListener(v -> adapter.remove(position));
            }
        };
        viewBinding.rvFlavor.setAdapter(adapter);
        viewBinding.rvFlavor.setLayoutManager(new GridLayoutManager(this, 1));//列数设置
    }

    private static final int REQUEST_PIC = 309;

    private void doChoosePhoto() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .theme(R.style.Matisse_Dracula)
                .countable(false)
                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .maxSelectable(1)
                .originalEnable(false)
                .imageEngine(new GlideEngine())
                .maxOriginalSize(10)
                .imageEngine(new PicassoEngine())
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "com.test.reggieadmin.fileprovider"))
                .forResult(REQUEST_PIC);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PIC && resultCode == Activity.RESULT_OK) {
            // 图片选择结果回调
            List<String> images = Matisse.obtainPathResult(data);
            image = images.get(0);
            Glide.with(this).load(image).into(viewBinding.iv);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv://菜品图片选择
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        //没有权限则申请权限
                        this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                                REQUEST_PIC);
                    } else {
                        //有权限直接执行,docode()不用做处理
                        doChoosePhoto();
                    }
                } else {
                    //小于6.0，不用申请权限，直接执行
                    doChoosePhoto();
                }
                break;
            case R.id.tv_categoryId://选择菜品分类
                basePopupView = new XPopup.Builder(this)
                        .asCustom(new FlavorCommentPopup(this))
                        .show();
                break;
            case R.id.btn_save://保存
                if (TextUtils.isEmpty(viewBinding.etName.getText().toString().trim())) {
                    ToastUtil.showCenter("菜品名称不能为空");
                } else if (TextUtils.isEmpty(viewBinding.tvCategoryId.getText().toString().trim())) {
                    ToastUtil.showCenter("请选择菜品分类");
                } else if (TextUtils.isEmpty(viewBinding.etPrice.getText().toString().trim())) {
                    ToastUtil.showCenter("菜品价格不能为空");
                } else if (image == null || "".equals(image) || TextUtils.isEmpty(image)) {
                    ToastUtil.showCenter("请添加菜品图片");
                } else {
                    if (id != null && !"".equals(id)) {
                        if (image.contains("/storage")) {
                            YUtils.showLoading("提交中...");
                            File file = new File(image);
                            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                            presenter.upload(body);//文件上传
                        } else {
                            YUtils.showLoading("提交中...");
                            Map<String, Object> mapAddDish = new HashMap<>();
                            mapAddDish.put("updateUser", employeeBean.getData().getUsername());
                            mapAddDish.put("status", 1);//状态 0：停售 1：起售
                            mapAddDish.put("name", viewBinding.etName.getText().toString().trim());//菜品名称
                            mapAddDish.put("categoryId", categoryId);//菜品分类
                            mapAddDish.put("price", viewBinding.etPrice.getText().toString().trim());//菜品价格
                            mapAddDish.put("flavors", flarors);//口味
                            mapAddDish.put("image", image);//菜品图片
                            mapAddDish.put("description", viewBinding.etDescription.getText().toString().trim());//菜品描述信息
                            mapAddDish.put("id", id);
                            presenter.updateDish(mapAddDish);//修改菜品
                        }
                    } else {
                        YUtils.showLoading("提交中...");
                        File file = new File(image);
                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                        presenter.upload(body);//文件上传
                    }
                }
                break;
            case R.id.btn_add_flavor://添加口味
                new XPopup.Builder(this)
                        .asCenterList("请选择一项", new String[]{"甜味", "温度", "忌口", "辣度"},
                                (position, text) -> {
                                    if (position == 0) {
                                        if (flarors.size() > 0) {
                                            for (int i = 0; i < flarors.size(); i++) {
                                                if ("甜味".equals(flarors.get(i).getName())) {
                                                    ToastUtil.showCenter("该口味已添加");
                                                    return;
                                                }
                                            }
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("甜味");
                                            String value = "[\"无糖\",\"少糖\",\"半塘\",\"多糖\",\"全糖\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        } else {
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("甜味");
                                            String value = "[\"无糖\",\"少糖\",\"半塘\",\"多糖\",\"全糖\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        }
                                    } else if (position == 1) {
                                        if (flarors.size() > 0) {
                                            for (int i = 0; i < flarors.size(); i++) {
                                                if ("温度".equals(flarors.get(i).getName())) {
                                                    ToastUtil.showCenter("该口味已添加");
                                                    return;
                                                }
                                            }
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("温度");
                                            String value = "[\"热饮\",\"常温\",\"去冰\",\"少冰\",\"多冰\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        } else {
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("温度");
                                            String value = "[\"热饮\",\"常温\",\"去冰\",\"少冰\",\"多冰\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        }
                                    } else if (position == 2) {
                                        if (flarors.size() > 0) {
                                            for (int i = 0; i < flarors.size(); i++) {
                                                if ("忌口".equals(flarors.get(i).getName())) {
                                                    ToastUtil.showCenter("该口味已添加");
                                                    return;
                                                }
                                            }
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("忌口");
                                            String value = "[\"不要葱\",\"不要蒜\",\"不要香菜\",\"不要辣\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        } else {
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("忌口");
                                            String value = "[\"不要葱\",\"不要蒜\",\"不要香菜\",\"不要辣\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        }
                                    } else if (position == 3) {
                                        if (flarors.size() > 0) {
                                            for (int i = 0; i < flarors.size(); i++) {
                                                if ("辣度".equals(flarors.get(i).getName())) {
                                                    ToastUtil.showCenter("该口味已添加");
                                                    return;
                                                }
                                            }
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("辣度");
                                            String value = "[\"不辣\",\"微辣\",\"中辣\",\"重辣\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        } else {
                                            DishDetailsBean.DataBean.FlavorsBean flavorsBean = new DishDetailsBean.DataBean.FlavorsBean();
                                            flavorsBean.setName("辣度");
                                            String value = "[\"不辣\",\"微辣\",\"中辣\",\"重辣\"]";
                                            flavorsBean.setValue(value);
                                            flavorsBean.setCreateUser(employeeBean.getData().getUsername());
                                            flavorsBean.setUpdateUser(employeeBean.getData().getUsername());
                                            flarors.add(flavorsBean);
                                        }
                                    }

                                    adapter.setNewData(flarors);
                                })
                        .show();
                break;
            case R.id.ll_back:
                finish();
                break;
            default:
                break;
        }
    }


    public class FlavorCommentPopup extends BottomPopupView {

        private RecyclerView rv;
        private BaseRVAdapter<CategoryListBean.DataBean> adapterFlavor;

        public FlavorCommentPopup(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.custom_bottom_popup_flavor;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            rv = findViewById(R.id.rv);

            adapterFlavor = new BaseRVAdapter<CategoryListBean.DataBean>(R.layout.item_flavor_name) {
                @Override
                public void onBindVH(BaseRVHolder holder, CategoryListBean.DataBean data, int position) {
                    TextView tv_name = holder.getView(R.id.tv_name);

                    tv_name.setText("" + data.getName());

                    tv_name.setOnClickListener(v -> {
                        categoryId = data.getId();
                        viewBinding.tvCategoryId.setText(data.getName());
                        basePopupView.dismiss();
                    });
                }
            };

            empty("暂无数据");

            rv.setAdapter(adapterFlavor);
            rv.setLayoutManager(new GridLayoutManager(AddDishActivity.this, 1));//列数设置
            adapterFlavor.setNewData(flavorList);
        }

        // 最大高度为Window的0.85
        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getAppHeight(getContext()) * .85f);
        }

        private void empty(String msg) {
            View empty = LayoutInflater.from(AddDishActivity.this).inflate(R.layout.layout_no_data, null, false);
            TextView tv_tip = empty.findViewById(R.id.tv_tip);
            tv_tip.setText(msg);
            adapterFlavor.setEmptyView(empty);
        }
    }

    @Override
    public void categoryListSuccess(CategoryListBean bean) {
        YUtils.hideLoading();
        if (bean.getCode() == 200) {
            flavorList = bean.getData();

            if (id != null && !"".equals(id)) {
                for (int i = 0; i < flavorList.size(); i++) {
                    if (categoryId.equals(flavorList.get(i).getId())) {
                        viewBinding.tvCategoryId.setText(flavorList.get(i).getName());
                    }
                }
            }
        } else {
            ToastUtil.showCenter(bean.getMsg());
        }
    }

    @Override
    public void onError(String msg) {
        YUtils.hideLoading();
        ToastUtil.showCenter(msg);
    }

    @Override
    public void addDishSuccess(BaseBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            setResult(Activity.RESULT_OK);
            finish();
        }
    }

    @Override
    public void uploadSuccess(BaseBean bean) {
        if (bean.getCode() == 200) {
            image = String.valueOf(bean.getData());
            Map<String, Object> mapAddDish = new HashMap<>();
            mapAddDish.put("updateUser", employeeBean.getData().getUsername());
            mapAddDish.put("status", 1);//状态 0：停售 1：起售
            mapAddDish.put("name", viewBinding.etName.getText().toString().trim());//菜品名称
            mapAddDish.put("categoryId", categoryId);//菜品分类
            mapAddDish.put("price", viewBinding.etPrice.getText().toString().trim());//菜品价格
            mapAddDish.put("flavors", flarors);//口味
            mapAddDish.put("image", image);//菜品图片
            mapAddDish.put("description", viewBinding.etDescription.getText().toString().trim());//菜品描述信息

            if (id != null && !"".equals(id)) {
                mapAddDish.put("id", id);
                presenter.updateDish(mapAddDish);//修改菜品
            } else {
                mapAddDish.put("createUser", employeeBean.getData().getUsername());
                presenter.addDish(mapAddDish);//新增菜品
            }
        } else {
            ToastUtil.showCenter(bean.getMsg());
        }
    }

    @Override
    public void dishDetailsSuccess(DishDetailsBean bean) {
        YUtils.hideLoading();
        if (bean.getCode() == 200) {
            viewBinding.etName.setText(bean.getData().getName());

            viewBinding.etPrice.setText("" + bean.getData().getPrice());

            flarors = (bean.getData().getFlavors());
            adapter.setNewData(flarors);

            image = bean.getData().getImage();
            Glide.with(this).load(API.kv.decodeString(State.ip) + "/common/download?name=" + image)
                    /*.diskCacheStrategy(DiskCacheStrategy.NONE)*/
                    .placeholder(R.drawable.icon_no_data).into(viewBinding.iv);

            viewBinding.etDescription.setText(bean.getData().getDescription());
        }
    }

    @Override
    public void updateDishSuccess(BaseBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            setResult(Activity.RESULT_OK);
            finish();
        }
    }
}